<template>
  <div class="page-box">
    <div class="ticketList-top-btn">
      <el-button v-if="tableList.length" @click="downTem()" icon="el-icon-download">模板下载</el-button>
      <el-button :loading="inporticketLoding" v-if="!inporticketLoding" @click="copyVal='';successNum=0;copyAlert=true" icon="el-icon-download">导入国际票</el-button>
    </div>
    <!-- 展示票弹框 -->
    <el-table ref="multipleTableTicket" :border="true" :data="copyList" empty-text="请点击导入国际票进行导入" style="width: 100%">
      <el-table-column width="60px" type="index" align="center">
      </el-table-column>
      <el-table-column v-for="(item, index) in tableList" :key="index" :label="item.label" :prop="item.prop" align="center">
      </el-table-column>
      <el-table-column align="center" label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status===true" type="success">成功</el-tag>
          <el-tag v-if="scope.row.status===false" type="danger">失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="msg" align="center" label="提示">
      </el-table-column>
    </el-table>
    <div class="bottom-btn">
      <el-button :loading="inporticketLoding" @click="startInporticket()" v-if="copyList.length&&successNum!=copyList.length" type="primary">开始导入</el-button>
    </div>
    <!-- 导内入门票 -->
    <el-dialog title="导入国际票 " :visible.sync="copyAlert" width="860px">
      <el-input type="textarea" :autosize="{ minRows: 10, maxRows: 13}" placeholder="请输入复制的内容" v-model="copyVal">
      </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="copyAlert = false">取 消</el-button>
        <el-button type="primary" @click="copyValFun()">下一步</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import importicketEng from "./importicketEng.js";
import servicePub from "@/api/servicePub";
import elementUIFun from "@/components/js/elementUIFun.js";
export default {
  data() {
    return {
      copyList: [], //复制的票列表
      tableList: [], //表格要渲染的数据字段
      inporticketLoding: false,
      copyVal: "", //票导入内容
      successNum: 0, //导入成功的数量
      copyAlert: false //复制弹框，
    };
  },
  computed: {
    thisActivityId() {
      return this.$store.state.activityId.thisActivityId;
    }
  },
  watch: {
    thisActivityId(a, b) {}
  },
  created() {
    this.getTableList();
  },
  methods: {
    // 得到要渲染的数据
    async getTableList() {
      this.tableList = JSON.parse(JSON.stringify(importicketEng));
    },
    downTem() {
      let that = this;
      require.ensure([], () => {
        const { export_json_to_excel } = require("./../../vendor/Export2Excel"); //这里必须使用绝对路径
        let tHeader = []; // 导出的表头名
        let filterVal = []; // 导出的表头字段名
        that.tableList.map(item => {
          tHeader.push(item.label);
          filterVal.push(item.prop);
        });
        const data = this.formatJson(filterVal, []);
        export_json_to_excel(tHeader, data, "导入国际票模板");
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    },
    // 复制导入解析内容
    async copyValFun() {
      try {
        if (!this.copyVal) {
          this.$message({
            message: "请输入内容",
            type: "warning"
          });
          return;
        }
        this.copyList = [];
        let data = this.copyVal;
        let datas = data.split("\n");
        this.copyList = [];
        const tableList = this.tableList;
        datas.map((item, index) => {
          let rows = item.split("\t");
          if (!rows[0] || !rows[2]) {
            return;
          }
          if (!rows.length) {
            return;
          }
          let copyItem = {};
          rows.map((rowsItem, rowsItemIndex) => {
            copyItem[tableList[rowsItemIndex]["prop"]] = rowsItem.trim();
          });
          this.copyList.push(copyItem);
        });

        if (!(await this.checkPhone()) || !(await this.checkID())) {
          this.copyList = [];
          return;
        }

        console.log(this.copyList);
        this.copyAlert = false;
      } catch (err) {
        console.log(err);
        this.copyVal = "";
        this.$message({
          message: "格式解析错误！请重试",
          type: "warning"
        });
      }
    },
    // 判断手机号是否正确
    checkPhone() {
      let photoIsAllTrue = true; //手机是否都正确
      for (let i = 0; i < this.copyList.length; i++) {
        const uTel = this.copyList[i].uTel;
        if (isNaN(uTel)) {
          photoIsAllTrue = false;
          this.$message({
            message: `请确定手机号码是否是纯数字或者有空格(查看第${i + 1}行)`,
            type: "warning"
          });
          break;
        }
        if (uTel.length > 14) {
          photoIsAllTrue = false;
          this.$message({
            message: `手机号码最多14位数字(查看第${i + 1}行)`,
            type: "warning"
          });
          break;
        }
      }
      return new Promise(resolve => {
        resolve(photoIsAllTrue);
      });
    },
    // 判断ID是否是纯数字
    checkID() {
      let value = true;
      const copyList = this.copyList;
      const check = ["pricegroupId", "ticketTypeId", "areaCode"]; //判断的字段
      for (let i = 0; i < copyList.length; i++) {
        const copyListFiled = Object.keys(copyList[i]);
        copyListFiled.map(item => {
          if (check.indexOf(item) != -1 && isNaN(copyList[i][item])) {
            value = false;
            return;
          }
        });
      }
      if (!value) {
        this.$message({
          message: "价格组ID或者票类型ID或者手机区号不是一个纯数字,请检查",
          type: "warning"
        });
      }
      return new Promise(resolve => {
        resolve(value);
      });
    },
    // 开始导入
    async startInporticket() {
      let errorData = [];
      if (this.successNum == this.copyList.length) {
        this.$message({
          message: "请重新复制内容导入",
          type: "warning"
        });
        return;
      }
      const confirm = await elementUIFun.$confirm("您确定开始导入？");
      if (!confirm) {
        return;
      }
      this.inporticketLoding = true;
      this.successNum = 0;
      //        POST参数
      for (let i = 0; i < this.copyList.length; i++) {
        if (!this.copyList[i].status) {
          let subData = {
            corpId: localStorage.getItem("corpId"),
            activityId: this.$store.state.activityId.thisActivityId,
            isPay: "pay",
            ...this.copyList[i]
          };
          subData.uTel =
            "+" + this.copyList[i].areaCode + "-" + this.copyList[i].uTel;
          console.log(subData);
          const res = await servicePub.importPersonalTicketList(subData);
          if (res.success) {
            this.$set(this.copyList[i], "status", true);
          } else {
            this.$set(this.copyList[i], "status", false);
            this.$set(this.copyList[i], "msg", res.errorMsg);
            errorData.push(this.copyList[i]);
          }
          this.successNum++;
        }

        let obj = {};
        this.tableList.map(item => {
          obj[item.prop] = item.label;
        });
        obj.status = "状态";
        obj.msg = "提示";
        if (this.successNum == this.copyList.length) {
          errorData.unshift(obj);
          let params = {
            errorType: "导入国际票",
            importInfo: JSON.stringify(errorData),
            isPay: "pay",
            isError: 1,
            activityId: this.$store.state.activityId.thisActivityId
          };
          if (errorData.length > 1) {
            const errorResult = await servicePub.errorFun(params);
            console.log(JSON.stringify(errorResult));
          }
        }
      }
      // console.log(this.copyList);
      this.inporticketLoding = false;
    }
  }
};
</script>
<style scoped>
.ticketList-top-btn {
  width: 100%;
  height: auto;
  margin: 10px 0px 20px 0px;
  display: flex;
  -webkit-display: flex;
  -webkit-justify-content: space-between;
  justify-content: space-between;
  -webkit-align-items: center;
  align-items: center;
}
.bottom-btn {
  display: flex;
  -webkit-display: flex;
  -webkit-justify-content: center;
  justify-content: center;
  -webkit-align-items: center;
  align-items: center;
  margin-top: 26px;
}
</style>